/**
*
* @author zzhijie
* @date 2021-07-01
*/

<template>
  <div class="uploader" v-loading="loading" @click="handleClick">
    <slot>
      <div class="remove" v-if="value" @click.stop="handleRemove"><i class="el-icon-delete"></i></div>
      <img class="img" :src="value" v-if="value"/>
      <div class="default" v-else>
        <i>+</i>
        <p>上传图片</p>
      </div>
    </slot>
    <input style="display: none" type="file" ref="file" @change="handleChange"></input>
  </div>
</template>

<script>
import {getRandomKey} from "@/utils/util";

export default {
  name: "uploader",
  props: {
    size: {
      type: Number,
      default: 5
    },
    onSuccess: {
      type: Function
    },
    onRemove: {
      type: Function
    },
    value: {
      type: String
    }
  },
  data() {
    return {
      loading: false,
    }
  },
  methods: {
    handleRemove() {
      this.onRemove && this.onRemove();
    },
    handleClick() {
      if (this.loading) return;
      this.$refs.file.click();
    },
    handleChange(e) {
      let [file] = e.target.files;
      if (file.size > this.size * 1024 * 1024) {
        return this.$message.warning('图片大小不能大于' + this.size + 'M');
      }
      if (!/(jpg|jpeg|png)/i.test(file.type)) {
        return this.$message.warning('图片格式必须为jpg或png');
      }
      this.handleUpload(file);
    },
    handleUpload(file) {
      this.loading = true;
      let fileName = getRandomKey(20) + "." + file.type.split("/")[1];
      this.ossClient.put("/images/" + fileName, file).then(res => {
        console.log(res);
        this.onSuccess && this.onSuccess(res);
        this.loading = false;
      }).catch(() => this.loading = false);
      this.$refs.file.value = "";
    }
  },
  mounted() {
  }
}
</script>

<style lang="scss" scoped>
.uploader {
  width: 60px;
  height: 60px;
  color: $primary;
  border: 1px solid #e5e5e5;
  background-color: #f2f4f6;
  text-align: center;
  cursor: pointer;
  position: relative;

  .remove {
    display: none;
    position: absolute;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
    background: rgba(0, 0, 0, .7);
    transition: all .2s;
    line-height: 58px;

    i {
      font-size: 18px;
      color: #fff;
    }
  }

  &:hover {
    .remove {
      display: block;
    }
  }

  .img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .default {
    height: 100%;
    text-align: center;
    font-size: 12px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    i {
      font-size: 25px;
      line-height: 25px;
    }
  }
}
</style>
